package org.Lin.service;

import org.Lin.dao.FriendListDAO;
import org.Lin.model.FriendList;
import org.Lin.util.LogUtil;

import java.sql.SQLException;
import java.time.LocalDateTime;
import java.util.List;

public class FriendService {

    private final FriendListDAO friendListDAO = new FriendListDAO();

    public boolean addFriend(int user1Id, int user2Id) {
        try {
            FriendList existing = findFriendship(user1Id, user2Id);
            if (existing != null) {
                return false; // 已是好友
            }
            FriendList fl = new FriendList();
            fl.setUser1Id(user1Id);
            fl.setUser2Id(user2Id);
            fl.setRelationStatus("正常");
            fl.setCreatedAt(LocalDateTime.now());
            fl.setLastModified(LocalDateTime.now());
            friendListDAO.insert(fl);

            LogUtil.logOperation("Friend", "add", "添加好友关系: " + user1Id + "-" + user2Id);
            return true;
        } catch (SQLException e) {
            e.printStackTrace();
            return false;
        }
    }

    public FriendList findFriendship(int user1Id, int user2Id) throws SQLException {
        List<FriendList> friends = friendListDAO.findByUserId(user1Id);
        for (FriendList f : friends) {
            if ((f.getUser1Id() == user1Id && f.getUser2Id() == user2Id) ||
                    (f.getUser1Id() == user2Id && f.getUser2Id() == user1Id)) {
                return f;
            }
        }
        return null;
    }
}
